module.exports = {
  meta: {
    type: "problem",
    docs: {
      description: `确保 this.$bus.$on 有对应的 this.$bus.$off
        例如this.$bus.$on("modalpassword-open", this.on_modalpassword_open); 对应 this.$bus.$off("modalpassword-open", this.on_modalpassword_open);`,
      recommended: false,
    },
    schema: [],
  },

  create(context) {
    const busOnCalls = []; // 存 this.$bus.$on 的节点
    const busOffCalls = []; // 存 this.$bus.$off 的节点

    function isThisBusCall(node, methodName) {
      return (
        node.type === "CallExpression" &&
        node.callee.type === "MemberExpression" &&
        node.callee.object.type === "MemberExpression" &&
        node.callee.object.object.type === "ThisExpression" &&
        node.callee.object.property.name === "$bus" &&
        node.callee.property.name === methodName
      );
    }

    return {
      CallExpression(node) {
        if (isThisBusCall(node, "$on")) {
          busOnCalls.push(node);
        }
        if (isThisBusCall(node, "$off")) {
          busOffCalls.push(node);
        }
      },

      "Program:exit"() {
        const offEvents = new Set(
          busOffCalls
            .map((call) => {
              const arg = call.arguments[0];
              return arg && arg.type === "Literal" ? arg.value : null;
            })
            .filter(Boolean)
        );

        for (const call of busOnCalls) {
          const event = call.arguments[0]?.value;
          if (event && !offEvents.has(event)) {
            context.report({
              node: call,
              message: `事件 "${event}" 已通过 this.$bus.$on 注册，但未通过 this.$bus.$off 移除`,
            });
          }
        }
      },
    };
  },
};
